import React, { Component, ComponentType } from "react";

export default class ErrorBoundry extends Component<
  { text?: string },
  {
    errorFlag: boolean;
  }
> {
  constructor(props: any) {
    super(props);
    this.state = {
      errorFlag: false,
    };
  }

  componentDidCatch(error: any, info: any) {
    console.log("error", error);
    console.log(info);
    this.setState({ errorFlag: true });
  }

  render() {
    // console.log(this.props.children);
    if (this.state.errorFlag)
      return (
        <h3 style={{ textAlign: "center", color: "skyblue" }}>出现错误哦</h3>
      );
    return this.props.children;
  }
}

// 不能过后直接返回组件。否则就是元素
export function errorCatch(
  Com: ComponentType,
  props?: {
    text?: string;
  }
) {
  return () => (
    <ErrorBoundry {...props}>
      <Com />
    </ErrorBoundry>
  );
}
